<?php
namespace addons\yexam\service;

use app\admin\model\yexam\Question;
use app\admin\model\yexam\Unit;

class Subject
{

    public $model;

    public function __construct()
    {
        $this->model = new \app\admin\model\yexam\Subject();
    }

    /**
     * 获取科目列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getSubjectList($page,$limit){
        $count = $this->model->where(['status'=>1])->count();
        if($page){
            $data = $this->model->where(['status'=>1])->page($page,$limit)->order("weigh asc")->select();
        }else{
            $data = $this->model->where(['status'=>1])->order("weigh asc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取当前科目下的章节
     */
    public function getUnitList($subject_id,$pid,$page,$limit){
        $model = new Unit();
        $count = $model->where(['status'=>1,'subject_id'=>$subject_id,'pid'=>$pid])->count();
        if($page){
            $data = $model->field("id,unit_name as name,is_last")->where(['status'=>1,'subject_id'=>$subject_id,'pid'=>$pid])->page($page,$limit)->order("sort asc")->select();
        }else{
            $data = $model->field("id,unit_name as name,is_last")->where(['status'=>1,'subject_id'=>$subject_id,'pid'=>$pid])->order("sort asc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取指定科目下章节练习的题目总数
     */
    public function getSubjectQuestionNum($subject_id){
        $questionModel = new Question();
        return $questionModel->where(['subject_id'=>$subject_id,'unit_id'=>['neq',0]])->count();
    }

    /**
     * 获取指定科目下的章节练习的题目完成数量
     */
    public function getSubjectQuestionTestNum($subject_id,$user_id){
        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.subject_id'=>$subject_id,'question.unit_id'=>['neq',0],"log.user_id"=>$user_id])->count();
    }

    /**
     * 获取指定科目下的章节练习的题目正确数量
     */
    public function getSubjectQuestionRightNum($subject_id,$user_id){
        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.subject_id'=>$subject_id,'question.unit_id'=>['neq',0],"log.state"=>1,"log.user_id"=>$user_id])->count();
    }
}